import BrowserService from '../../browser.service';
import { AgileAddBacklogCConfig } from '../../config';
import { consoleLog, delay } from '../../utils';
const {
  title,
  pageUrl,
  projectName,
  placeholder,
  from,
  operation,
  testPage,
  screenshotName,
} = AgileAddBacklogCConfig;
export default class AgileAddBacklogController extends BrowserService {
  constructor() {
    super();
  }
  async init() {
    await this.exportConfig(title, from);
    await this.goAddBacklogPage();
    await this.openAddDialog();
  }
  async goAddBacklogPage() {
    // 比对当前页面的url如果不是项目页面访问项目页面
    const nowPageUrl = this.page.url();
    if (nowPageUrl !== pageUrl) {
      await this.page.goto(pageUrl, { waitUntil: 'networkidle' });
    }
    // 因为标识是唯一的不能重复的[比对项目名与标识需要同时存在]
    const projectNameVisible = await this.page.isVisible(
      `tbody tr td span:has-text("${projectName}")`
    );
    const placeholderVisible = await this.page.isVisible(
      `tbody tr td span:has-text("${placeholder}")`
    );
    if (projectNameVisible && placeholderVisible) {
      // 点击项目列表跳转到需求页面
      await this.page.click(`tbody tr td span:has-text("${placeholder}")`);
    } else {
      await consoleLog(`Agile添加用户故事测试 找不到所属项目`, this.logPath);
    }
  }
  async openAddDialog() {
    await this.setSelect(operation);
    const isVisible = await this.page.isVisible(
      '.dialog-title:has-text("新建用户故事")'
    );
    if (isVisible) {
      await delay(2000);
      await this.addBacklog();
    } else {
      console.log('弹框加载失败');
    }
  }
  async addBacklog() {
    await this.submitForm(from);
    const fromDataState = await this.expectFormData(from);
    if (fromDataState) {
      await this.expectProject();
    }
  }
  async expectProject() {
    const isVisible = await this.page.isVisible(
      '.dialog-title:has-text("新建用户故事")'
    );
    const isNotify = await this.page.isVisible('.thy-notify-content');
    // 弹框消失证明添加成功
    if (isNotify && !isVisible) {
      const errText = await this.page.innerText('.thy-notify-content span');
      await consoleLog(`Agile添加用户故事测试 ${errText}`, this.logPath);
    } else {
      await this.expectTest();
      await this.screenshot(screenshotName);
    }
  }
  // 这里比较复杂需要自己写验证测试规则
  async expectTest() {
    await this.clickGroup(testPage.btnGroup);
    await this.expectTableTestResult(testPage.table);
  }
}

/**
 * 新建用户故事
 * 1. 登录用户，保证用户处于登录状态[所有的页面测试都需要在登录状态下进行]
 * 2. 访问项目列表页面，点击需要项目进入需求页面
 * 3. 点击新建，选择用户故事等待弹框弹出
 * 4. 操作表单
 * 5. 查看需求列表中有没有刚才创建的项目
 * 6. 比对列表上的内容是否正确[选择按照时间排序]
 */
